<template>
  <div class="app-container" style="padding: 10px">
    <el-row :gutter="10">
      <el-col :span="4" :xs="24">
        <el-card>
          <div class="head-container">
            <el-input placeholder="输入关键字进行过滤" clearable prefix-icon="el-icon-search" style="margin-bottom: 20px" />
          </div>
          <div style="height: 73vh; overflow: auto">
            <el-tree v-if="refreshTree" :data="categories" :props="{ value: 'id', label: 'title' }"
              :expand-on-click-node="false" ref="tree" node-key="id" default-expand-all highlight-current
              :current-node-key="queryParams.knowledgeCategoryId" @node-click="handleNodeClick" />
          </div>
        </el-card>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-card class="box-card" shadow="false">
          <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="45px">
            <el-form-item label="标签" prop="tag">
              <el-select v-model="queryParams.tag" placeholder="请选择类型" clearable filterable>
                <el-option v-for="dict in tags" :key="dict.id" :label="dict.tagName" :value="dict.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
                <el-option v-for="dict in dict.type.exam_question_type" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="题目" prop="topic">
              <el-input v-model="queryParams.topic" placeholder="请输入题目" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleQuery"> 搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery"> 重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">
                新建试题
              </el-button>
            </el-col>
            <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
          </el-row>

          <el-table v-loading="loading" :data="list" border>
            <el-table-column type="index" align="center" width="55" />
            <el-table-column label="题目" prop="topic" width="500"/>
            <el-table-column label="知识分类" prop="knowledgeCategories" width="180" />
            <el-table-column label="标签" width="160px" align="center" prop="tag" :formatter="tagTransform" />
            <el-table-column label="类型" width="120px" align="center">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.exam_question_type" :value="scope.row.type" />
              </template>
            </el-table-column>
            <!-- <el-table-column label="创建人" prop="createBy" align="center" width="150" /> -->
            <el-table-column label="创建时间" prop="createTime" align="center" width="180" />
            <el-table-column label="操作" align="center" width="220" fixed="right">
              <template slot-scope="scope">
                <el-button icon="el-icon-view" size="mini" type="text" @click="handleInfo(scope.row)">
                  详情
                </el-button>
                <el-button icon="el-icon-edit" size="mini" type="text" @click="handleUpdate(scope.row)">
                  修改
                </el-button>
                <el-button icon="el-icon-delete" size="mini" type="text" @click="handleDelete(scope.row.id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum"
            :total="total" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>


    <el-drawer :visible.sync="drawerShow" :title="drawerTitle">
      <div style="padding: 20px">
        <el-form :model="params" label-position="top">
          <el-form-item label="试题类型" required>
            <el-select v-model="params.type" placeholder="请选择试题类型" @change="typeChange" :disabled="isEdit"
              style="width: 100%">
              <el-option v-for="dict in dict.type.exam_question_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="params.type" label="* 知识分类" prop="knowledgeCategoryId">
            <el-cascader v-model="params.knowledgeCategoryId" placeholder="请选择知识分类" style="width: 100%"
              :options="categories" :props="{ value: 'id', label: 'title' }" />
          </el-form-item>
          <el-form-item label="试题标签" v-if="params.type">
            <div style="display: flex">
              <el-select multiple style="width: 100%" v-model="checkTags" placeholder="请选择试题标签">
                <el-option v-for="item in tags" :key="item.id" :label="item.tagName" :value="item.id">
                </el-option>
              </el-select>
              <el-popover style="margin-left: 5px" placement="top" width="160" v-model="addTagShow">
                <el-input size="small" v-model="addTagName" placeholder="请输入标签名称"></el-input>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="addTagShow = false">取消</el-button>
                  <el-button type="text" size="mini" @click="addTag">确定</el-button>
                </div>
                <el-button icon="el-icon-plus" slot="reference" plain />
              </el-popover>
            </div>
          </el-form-item>
          <el-form-item label="试题内容" v-if="params.type" required>
            <div style="padding: 0 20px">
              <!-- 单选题 -->
              <div v-show="params.type === '1'">
                <el-form :model="params">
                  <el-form-item label="题目" required>
                    <el-input v-model="params.topic" type="textarea" placeholder="请输入题目" />
                  </el-form-item>
                  <el-form-item label="选项" required>
                    <div v-for="item in options" style="display: flex;align-items: center; margin-bottom: 10px">
                      <span style="color: #333333; margin-right: 10px">
                        {{ item.value }}.
                      </span>
                      <el-input type="textarea" v-model="item.label" :placeholder="`请输入选项${item.value}`" />
                    </div>
                    <div>
                      <el-button type="text" @click="addOption">
                        <div style="display: flex; align-items: center">
                          <i class="el-icon-circle-plus-outline" />
                          <span>添加选项</span>
                        </div>
                      </el-button>
                      <el-button type="text" @click="removeOption" :disabled="options.length === 0">
                        <div style="display: flex; align-items: center">
                          <i class="el-icon-remove-outline" />
                          <span>移除选项</span>
                        </div>
                      </el-button>
                    </div>
                  </el-form-item>
                  <el-form-item label="答案" required>
                    <el-radio-group v-model="params.answer">
                      <el-radio v-for="item in options" :label="item.value">
                        <span>
                          {{ item.value }}
                        </span>
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-form>
              </div>
              <!-- 多选题 -->
              <div v-show="params.type === '2'">
                <el-form :model="params">
                  <el-form-item label="题目" required>
                    <el-input v-model="params.topic" type="textarea" placeholder="请输入题目" />
                  </el-form-item>
                  <el-form-item label="选项" required>
                    <div v-for="item in options" style="display: flex;align-items: center; margin-bottom: 10px">
                      <span style="color: #333333; margin-right: 10px">
                        {{ item.value }}.
                      </span>
                      <el-input type="textarea" v-model="item.label" :placeholder="`请输入选项${item.value}`" />
                    </div>
                    <div>
                      <el-button type="text" @click="addOption">
                        <div style="display: flex; align-items: center">
                          <i class="el-icon-circle-plus-outline" />
                          <span>添加选项</span>
                        </div>
                      </el-button>
                      <el-button type="text" @click="removeOption" :disabled="options.length === 0">
                        <div style="display: flex; align-items: center">
                          <i class="el-icon-remove-outline" />
                          <span>移除选项</span>
                        </div>
                      </el-button>
                    </div>
                  </el-form-item>
                  <el-form-item label="答案" required>
                    <el-checkbox-group v-model="answers">
                      <el-checkbox v-for="item in options" :label="item.value" />
                    </el-checkbox-group>
                  </el-form-item>
                </el-form>
              </div>
              <!-- 判断题 -->
              <div v-show="params.type === '3'">
                <el-form :model="params">
                  <el-form-item label="题目" required>
                    <el-input v-model="params.topic" type="textarea" placeholder="请输入题目" />
                  </el-form-item>
                  <el-form-item label="答案" required>
                    <el-radio-group v-model="params.answer">
                      <el-radio v-for="item in options" :label="item.value">
                        <span>
                          {{ item.label }}
                        </span>
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-form>
              </div>
              <!-- 填空题 -->
              <div v-show="params.type === '4'">
                <el-form :model="params">
                  <el-form-item label="题目" required>
                    <el-input v-model="params.topic" type="textarea" placeholder="请输入题目" />
                    <el-button type="text" @click="addBlank">
                      <div style="display: flex; align-items: center">
                        <i class="el-icon-circle-plus-outline" />
                        <span>插入填空</span>
                      </div>
                    </el-button>
                  </el-form-item>
                  <el-form-item label="答案" required>
                    <div style="margin: 10px 0; display: flex; align-items: center" v-for="(item, index) in answers">
                      <span style="margin-right: 10px">{{ index + 1 }}.</span>
                      <el-input v-model="item.answer" :placeholder="`请输入填空答案`" />
                    </div>
                  </el-form-item>
                </el-form>
              </div>
              <!-- 简答题 -->
              <div v-show="params.type === '5'">
                <el-form :model="params.topic">
                  <el-form-item label="题目" required>
                    <el-input v-model="params.topic" type="textarea" placeholder="请输入题目" />
                  </el-form-item>
                  <el-form-item label="答案" required>
                    <el-input v-model="params.answer" type="textarea" placeholder="请输入答案" />
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </el-form-item>
        </el-form>

        <div style="display: flex; justify-content: right; margin-top: 20px" v-if="params.type">
          <el-button @click="cancel">
            取 消
          </el-button>
          <el-button type="primary" @click="submitCheck">
            保 存
          </el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 详情抽屉 -->
    <el-dialog :visible.sync="drawerInfoShow" title="试题详情" width="500px">
      <div>
        <div style="display: flex; align-items: center">
          <dict-tag :options="dict.type.exam_question_type" :value="info.type" size="mini" />
          <div style="color: #333333; display: flex; align-items: center; font-weight: bold">
            <span style="margin-left: 5px">
              {{ info.topic }}
            </span>
          </div>
        </div>
        <div v-show="info.type === '1' || info.type === '2'">
          <div style="margin: 20px; color: #666666">
            <div v-for="item in options" style="margin: 5px 0">
              <span style="margin-right: 5px">{{ item.value }}.</span>
              <span>{{ item.label }}</span>
            </div>
          </div>
          <div style="color: orange;">
            答案：{{ info.answer }}
          </div>
        </div>
        <div v-show="info.type === '3'">
          <div style="color: orange;margin-top: 20px">
            <span>答案：</span>
            {{ info.answer === 'T' ? '正确' : '错误' }}
          </div>
        </div>
        <div v-show="info.type === '4'">
          <div style="color: orange;margin-top: 20px">
            <span>答案：</span>
            <div style="margin: 5px 0" v-for="(item, index) in answers">
              {{ index + 1 }}. {{ item.answer }}
            </div>
          </div>
        </div>
        <div v-show="info.type === '5'">
          <div style="color: orange;margin-top: 20px">
            <span>答案：</span>
            <div style="margin: 5px 0">
              {{ info.answer }}
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="js">
import { addOrUpdate, deleteQuestion, pageList } from "@/api/exam/questionLibrary";
import { addTag, categoryTreeList, tagList } from "@/api/edu/trainPlan";

export default {
  name: 'QuestionLibrary',
  dicts: ['exam_question_type'],
  data() {
    return {
      addTagShow: false,
      addTagName: '',
      loading: false,
      // 查询展示
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      list: [],
      typeOptions: [],
      params: {
        type: '',
        topic: '',
        options: '',
        answer: ''
      },
      answers: [],
      options: [],
      info: {},
      isEdit: false,
      letters: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
      drawerShow: false,
      drawerTitle: "",
      drawerInfoShow: false,
      tags: [],
      checkTags: [],
      refreshTree: true,
      categories: []
    }
  },
  created() {
    this.handleQuery()
    categoryTreeList().then(res => {
      this.categories = res.data.rows
    })
  },
  methods: {
    tagTransform(row) {
      if (row.tag) {
        const tagSplit = row.tag.split(',')
        let tagName = "";
        tagSplit.forEach(t => {
          this.tags.forEach(tag => {
            if (tag.id === t) {
              tagName += tag.tagName + ' | '
            }
          })
        })
        return tagName.substring(0, tagName.length - 3)
      } else {
        return ""
      }
    },
    getTags() {
      tagList().then(res => {
        this.tags = res.data
      })
    },
    addTag() {
      addTag(this.addTagName).then(res => {
        this.addTagShow = false
        this.getTags()
      })
    },
    handleNodeClick(e) {
      this.queryParams.knowledgeCategoryId = e.id
      this.getList()
    },
    querySearch(queryString, cb) {
      const tags = this.tags
      const results = queryString ? tags.filter(this.createFilter(queryString)) : tags;
      // 调用 callback 返回建议列表的数据
      results.forEach(e => {
        e.value = e.tagName
      })
      cb(results);
    },
    createFilter(queryString) {
      return (tag) => {
        return (tag.tag.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    resetQuestionForm() {
      return new Promise(res => {
        this.params = {
          type: '',
          topic: '',
          options: '',
          answer: ''
        }
        this.options = []
        this.answers = []
        res()
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
      this.getTags()
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10
      }
      this.getList()
    },
    getList() {
      this.loading = true
      this.list = []
      pageList(this.queryParams).then(res => {
        this.list = res.rows
        this.total = res.total
        this.loading = false
      })
    },
    handleParams(row) {
      this.options = JSON.parse(row.options)
      if (row.type === '2') {
        this.answers = row.answer.split(",")
      } else if (row.type === '4') {
        this.answers = JSON.parse(row.answer)
      }
    },
    handleInfo(row) {
      this.info = row
      this.handleParams(row)
      this.drawerInfoShow = true
    },
    handleAdd() {
      this.isEdit = false
      this.resetQuestionForm()
      this.drawerTitle = '新建试题'
      this.drawerShow = true
    },
    handleUpdate(row) {
      this.isEdit = true
      this.params = { ...row }
      if (this.params.tag) {
        this.checkTags = this.params.tag.split(",")
      }
      if (this.params.knowledgeCategoryId) {
        this.params.knowledgeCategoryId = this.params.knowledgeCategoryId.split(",")
      }
      this.handleParams(row)
      this.drawerTitle = '修改试题'
      this.drawerShow = true
    },
    handleDelete(id) {
      this.$confirm('是否删除该试题?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteQuestion(id).then(res => {
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
      })
    },
    cancel() {
      this.drawerShow = false
    },
    submitCheck() {
      if (!this.params.knowledgeCategoryId || this.params.knowledgeCategoryId.length === 0) {
        this.$message({
          type: "warning",
          message: "请选择知识分类"
        })
        return
      } else {
        this.params.knowledgeCategoryId = this.params.knowledgeCategoryId.toString()
      }
      if (!this.params.topic) {
        this.$message({
          type: 'warning',
          message: '请完善试题题目'
        })
        return
      }
      const type = this.params.type
      if (type === '1') { // 单选题参数校验
        if (this.options.length === 0) {
          this.$message({
            type: 'warning',
            message: `请添加至少一个选项`
          })
          return
        } else {
          try {
            this.options.forEach(o => {
              if (!o.label) {
                this.$message({
                  type: 'warning',
                  message: `请完善选项${o.value}`
                })
                throw new Error()
              }
            })
          } catch (e) {
            return;
          }
        }
        if (!this.params.answer) {
          this.$message({
            type: 'warning',
            message: '请选择试题答案'
          })
        }
      } else if (type === '2') { // 多选题参数校验
        if (this.options.length === 0) {
          this.$message({
            type: 'warning',
            message: `请添加至少一个选项`
          })
          return
        } else {
          try {
            this.options.forEach(o => {
              if (!o.value) {
                this.$message({
                  type: 'warning',
                  message: `请完善选项${o.label}`
                })
                throw new Error()
              }
            })
          } catch (e) {
            return;
          }
        }
        if (this.answers.length === 0) {
          this.$message({
            type: 'warning',
            message: '请选择试题答案'
          })
          return
        }
        this.params.answer = this.answers.sort().toString()
      } else if (type === '4') {
        if (this.answers.length === 0) {
          this.$message({
            type: 'warning',
            message: '请插入至少一个填空'
          })
          return
        }
        this.answers.forEach(o => {
          if (!o.answer) {
            this.$message({
              type: 'warning',
              message: `请完善答案`
            })
            throw new Error()
          }
        })
        this.params.answer = JSON.stringify(this.answers)
      } else {
        if (!this.params.answer) {
          this.$message({
            type: 'warning',
            message: `请完善答案`
          })
          throw new Error()
        }
      }
      if (this.checkTags.length > 0) {
        this.params.tag = this.checkTags.toString()
      }
      this.params.options = JSON.stringify(this.options)
      this.submitForm()
    },
    submitForm() {
      console.log(this.params)
      addOrUpdate(this.params).then(res => {
        this.drawerShow = false
        this.getList()
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      })
    },
    typeChange(e) {
      this.params = {
        type: e,
        topic: '',
        options: '',
        answer: ''
      }
      this.options = []
      this.answers = []
      if (e === '1' || e === '2') {
        for (const i in [1, 1, 1, 1]) {
          this.addOption()
        }
      } else if (e === '3') {
        this.options.push({
          value: 'T',
          label: '正确'
        })
        this.options.push({
          value: 'F',
          label: '错误'
        })
        this.params.answer = 'T'
      }
    },
    addOption() {
      this.options.push({
        value: this.letters[this.options.length],
        label: ''
      })
    },
    removeOption() {
      this.options.splice(this.options.length - 1, 1)
    },
    addBlank() {
      let index = `【填空】`
      this.params.topic += index
      this.answers.push({
        answer: ''
      })
    }
  }
}
</script>

<style scoped></style>
